<?php
/**
* product.php
*
* Create on 2014-12-26
* Create by TT
*/
namespace haibao\cms\data;


class Product extends \haibao\cms\data\BaseMysql{

	public function __construct(){
		parent::__construct('\haibao\cms\model\data\Product');
	}
	
	/**
	 * 通过单品ID查询单品库信息
	 */
	public function getProductInfoByIds($idStr){
		 $sql = "SELECT
				a.Id,
				a.ProductName,
				a.PicId,
				b.FileName,
				b.Description,
				b.Width,
				b.Height,
				b.Description,
				c.BrandId,
				d.Season,
				d.SeasonYear,
				d.ProductSeries
			FROM
				ProductModel AS a
			left join Product as d on a.ProductId = d.Id
			LEFT JOIN ImageLibrary AS b ON a.PicId = b.Id
			LEFT JOIN ProductBrandGroup AS c ON a.ProductId = c.ProductId
			WHERE
				a.Id IN ($idStr)";
//		$sql = "SELECT
//            	a.Id,
//            	a.Name as ProductName,
//            	e.ImageId as PicId,
//            	b.FileName,
//            	b.Description,
//            	b.Width,
//            	b.Height,
//            	b.Description,
//            	c.BrandId,
//            	d.Season,
//            	d.SeasonYear,
//            	d.ProductSeries
//            FROM
//            	Goods AS a
//            LEFT JOIN Product_New AS d ON a.ProductId = d.Id
//            LEFT JOIN GoodsImage as e on e.GoodsId = a.Id
//            LEFT JOIN ImageLibrary AS b ON e.ImageId = b.Id
//            LEFT JOIN ProductBrandGroup_New AS c ON a.ProductId = c.ProductId
//            WHERE
//            	a.Id IN ($idStr)";
		$productResult = $this->query($sql);
		$productInfo = array();
		while($row = $productResult->fetch_assoc()){
			$productInfo[$row['Id']] = $row;
		}
		return $productInfo;
	}
	
	/**
	 * 
	 */
	public function getProductValueByIds($productIdStr,$isSign = false){
	    $sqlValue = "SELECT
                    ProductModelId,PropertyValue
                FROM
                    ProductModelProperty
                WHERE
                    PropertyId in (
                        SELECT
                            Id
                        FROM
                            ProductCategoryProperty
                        WHERE
                            Id IN (
                                SELECT
                                    PropertyId
                                FROM
                                    ProductModelProperty AS a
                                WHERE
                                    ProductModelId in ($productIdStr)
                            )
                        AND PropertyName LIKE '%价格%'
                    )
                AND ProductModelId in ($productIdStr)";
	    $productResult = $this->query($sqlValue);
		$productValue = array();
		while($row = $productResult->fetch_assoc()){
			$productValue[$row['ProductModelId']] = $row['PropertyValue'];
		}
		
		$sqlValueType = "SELECT
                            ProductModelId,PropertyValue
                        FROM
                            ProductModelProperty
                        WHERE
                            PropertyId in (
                                SELECT
                                    Id
                                FROM
                                    ProductCategoryProperty
                                WHERE
                                    Id IN (
                                        SELECT
                                            PropertyId
                                        FROM
                                            ProductModelProperty AS a
                                        WHERE
                                            ProductModelId in ($productIdStr)
                                    )
                                AND PropertyName LIKE '%货币%'
                            )
                        AND ProductModelId in ($productIdStr)";
		$productResult = $this->query($sqlValueType);
		$productValueType = array();
		while($row = $productResult->fetch_assoc()){
		    $productValueType[$row['ProductModelId']] = $row['PropertyValue'];
		}
		if($productValue){
		    foreach($productValue as $key=>$val){
		        if(isset($productValueType[$key]) && !empty($val)){
		            if($isSign == true){
		                if($productValueType[$key] == 'RMB'){
		                    $productValueType[$key] = '￥';
		                }else if($productValueType[$key] == 'USD'){
		                    $productValueType[$key] = '$';
		                }else if($productValueType[$key] == 'EUR'){
		                    $productValueType[$key] = '€';
		                }else if($productValueType[$key] == 'GBP'){
		                    $productValueType[$key] = '£';
		                }else if($productValueType[$key] == 'HKD'){
		                    $productValueType[$key] = 'HK$';
		                }
		                $productValue[$key] = $productValueType[$key].$val;
		            }else{
		                $productValue[$key] = $productValueType[$key].' '.$val;
		            }
		        }
		    }
		}
		return $productValue;
	}
	
	/**
	 * 添加单品
	 * @param \haibao\cms\model\data\Product $model	单品实体
	 * @param array $brandIds	所属品牌ID
	 * @param string $userName	操作用户名
	 */
	public function addProduct($model,$brandIds,$userName){
		parent::add($model);
		
		$arrValues = array();
		$arrSql = array();
		foreach($brandIds as $id){
			array_push($arrSql,'(%s,%s)');
			array_push($arrValues,$id);
			array_push($arrValues,$model->Id);
		}
		
		$sql = "insert into ProductBrandGroup (BrandId,ProductId) values";
		$sql .= implode(',', $arrSql);
		$this->query($sql,$arrValues);		
		
		if(\haibao\classlibrary\cms\Config::getConfig(\haibao\classlibrary\cms\Config::SYNC_OLD)){
			$oldBrandIds = $this->getOldBrandId($brandIds);
			$this->setConfig( \haibao\classlibrary\cms\Config::CLASSLIBRARY_CONFIG_MYSQL_HAIBAO_ARTICLE );
			//添加brand_product_group
			$sql = 'insert into brand_product_group (username,date,status) values(%s,%s,%s)';
			$arrValues = array($userName,$model->CreateTime->format('Y-m-d H:i:s'),1);
			$this->query($sql,$arrValues);
			$groupId = $this->getDb()->insert_id;
			
			//添加brand_group_brand
			$arrValues = array();
			$arrSql = array();
			foreach($oldBrandIds as $id){
				array_push($arrSql,'(%s,%s)');
				array_push($arrValues,$id);
				array_push($arrValues,$groupId);
			}
			$sql = "insert into brand_group_brand (brand_id,group_id) values";
			$sql .= implode(',', $arrSql);
			$this->query($sql,$arrValues);
			
			//添加新老数据对应表DataMigrationMap
			$this->setConfig( \haibao\classlibrary\cms\Config::CLASSLIBRARY_CONFIG_MYSQL_HAIBAO_CMS );
			$sql = "insert into DataMigrationMap (TableName,PrimaryKey,OldPrimaryKey) values(%s,%s,%s)";
			$arrValues = array($model->getTableName(),$model->Id,$groupId);
			$this->query($sql,$arrValues);
		}
	}
	
	/**
	 * 修改产品
	 * @param int $id	单品ID
	 * @param array $arrSet 需要修改的字段
	 * @param array $brandIds	所属品牌ID
	 * @param int $categoryChange	是否修改类别
	 */
	public function updateProduct($id, $arrSet,$brandIds,$categoryChange = 0,$userName = ''){
		self::beginTranscation();
		try{
			parent::updateById($id, $arrSet);
			
			if($categoryChange){
				$sql = 'delete from ProductModelProperty where ProductModelId in (select Id from ProductModel where ProductId=%s)';
				$this->query($sql,array($id));
			}
			
			$sql = 'delete from ProductBrandGroup where ProductId=%s';
			$this->query($sql,array($id));
				
			$arrValues = array();
			$arrSql = array();
			foreach($brandIds as $brandId){
				array_push($arrSql,'(%s,%s)');
				array_push($arrValues,$brandId);
				array_push($arrValues,$id);
			}
			$sql = "insert into ProductBrandGroup (BrandId,ProductId) values";
			$sql .= implode(',', $arrSql);
			$this->query($sql,$arrValues);
		}catch (\Exception $e){
			$this->rollback();
			throw $e;
		}
		$this->endTranscation();
		
		if(\haibao\classlibrary\cms\Config::getConfig(\haibao\classlibrary\cms\Config::SYNC_OLD)){
			//修改老记录
			$oldBrandIds = $this->getOldBrandId($brandIds);
			$productModel = parent::getOneById($id);
			$tableName = $productModel->getTableName();
			$sql = 'select OldPrimaryKey from DataMigrationMap where TableName="'.$tableName.'" and PrimaryKey =%s';
			$result = $this->query($sql,array($id));
			$oldGroupId = 0;
			while ($result->fetch_assoc())
			{
				$oldGroupId = $result->getData('OldPrimaryKey');
			}

			if($oldGroupId){
				$this->setConfig( \haibao\classlibrary\cms\Config::CLASSLIBRARY_CONFIG_MYSQL_HAIBAO_ARTICLE );
				$sql = 'update brand_product_group set username=%s where id=%s';
				$this->query($sql,array($productModel->ProductName,$oldGroupId));
				
				$sql = 'delete from brand_group_brand where group_id=%s';
				$this->query($sql,array($oldGroupId));
				
				$arrValues = array();
				$arrSql = array();
				foreach($oldBrandIds as $id){
					array_push($arrSql,'(%s,%s)');
					array_push($arrValues,$id);
					array_push($arrValues,$oldGroupId);
				}
				$sql = "insert into brand_group_brand (brand_id,group_id) values";
				$sql .= implode(',', $arrSql);
				$this->query($sql,$arrValues);
				
				$sql = 'update brand_product set brand_id_up=%s,season=%s,season_year=%s,product_line=%s,material=%s,fashelement=%s,color=%s,status=%s where group_id=%s';
				$arrValues = array($productModel->SuperBrandId,$productModel->Season,$productModel->SeasonYear,$productModel->ProductSeries,$productModel->Material,$productModel->FashionElement,$productModel->Color,$productModel->Status,$oldGroupId);
				$this->query($sql,$arrValues);
			} else {
				$this->setConfig( \haibao\classlibrary\cms\Config::CLASSLIBRARY_CONFIG_MYSQL_HAIBAO_ARTICLE );
				//添加brand_product_group
				$sql = 'insert into brand_product_group (username,date,status) values(%s,%s,%s)';
				$arrValues = array($userName,new \DateTime(),1);
				$this->query($sql,$arrValues);
				$groupId = $this->getDb()->insert_id;
					
				//添加brand_group_brand
				$arrValues = array();
				$arrSql = array();
				foreach($oldBrandIds as $brandId){
					array_push($arrSql,'(%s,%s)');
					array_push($arrValues,$brandId);
					array_push($arrValues,$groupId);
				}
				$sql = "insert into brand_group_brand (brand_id,group_id) values";
				$sql .= implode(',', $arrSql);
				$this->query($sql,$arrValues);
				
				//添加新老数据对应表DataMigrationMap
				$this->setConfig( \haibao\classlibrary\cms\Config::CLASSLIBRARY_CONFIG_MYSQL_HAIBAO_CMS );
				$sql = "insert into DataMigrationMap (TableName,PrimaryKey,OldPrimaryKey) values(%s,%s,%s)";
				$arrValues = array($tableName,$id,$groupId);
				$this->query($sql,$arrValues);
			}
		}
	}
	
	public function updateProductStatus($id,$status = \haibao\cms\model\data\product::STATUS_ENABLE){
		self::beginTranscation();
		try{
			$sql = 'update Product set Status=%s where Id=%s';
			$arrValues = array($status,$id);
			$this->query($sql,$arrValues);
			
			$modelData = new \haibao\cms\data\ProductModel();
			$modelData->updateStatusByProductId($id,$status);
		}catch (\Exception $e){
			$this->rollback();
			throw $e;
		}
		$this->endTranscation();
	}
	
	/**
	 * 通过单品ID得到对应的品牌ID
	 * @param int $productId
	 */
	public function getBrandIdByProductId($productId){
		$sql = 'select BrandId from ProductBrandGroup where ProductId=%s';
		$result = $this->query($sql,array($productId));
		$brandIds = array();
		while ($result->fetch_assoc())
		{
			$brandIds[] = $result->getData('BrandId');
		}
		
		return $brandIds;
	}
	
	private function getOldBrandId($brandIds,$isNewId = true){
		$oldBrandIds = array();
		$str = preg_replace('/(\d+)/', '%s', implode(',', $brandIds));
		$sql="select OldPrimaryKey,PrimaryKey from DataMigrationMap where ";
		$where = " TableName = 'Brand' and PrimaryKey in (".$str.")";
		if(!$isNewId){
			$where = " TableName = 'Brand' and OldPrimaryKey in (".$str.")";
		}
		$result = $this->query($sql.$where, $brandIds);
		$primaryTag = array();
		while ($result->fetch_assoc()){
			$oldBrandIds[$result->getData('PrimaryKey')] = $result->getData('OldPrimaryKey');
		}
		if(!$isNewId){
			$oldBrandIds = array_flip($oldBrandIds);
		}
		return $oldBrandIds;
	}
	
	/**
	 * 获得老的单品Id
	 * @param array $productIds
	 * @param bool $isNewId
	 * @return 
	 */
	public function getOldproductId($productIds,$isNewId = true){
			$oldProductIds = array();
			$str = preg_replace('/(\d+)/', '%s', implode(',', $productIds));
			$sql="select OldPrimaryKey,PrimaryKey from DataMigrationMap where ";
			$where = " TableName = 'ProductModel' and PrimaryKey in (".$str.")";
			if(!$isNewId){
				$where = " TableName = 'ProductModel' and OldPrimaryKey in (".$str.")";
			}
			$result = $this->query($sql.$where, $productIds);
			$primaryTag = array();
			while ($result->fetch_assoc()){
				$oldProductIds[$result->getData('PrimaryKey')] = $result->getData('OldPrimaryKey');
			}
			if(!$isNewId){
				$oldProductIds = array_flip($oldProductIds);
			}
			return $oldProductIds;
	
	}

	public function getBrandInfoByProductIds($productIds){
		$str = preg_replace('/(\d+)/', '%s', implode(',', $productIds));
		$resArr = array();
		$sql = 'select b.NameCn,b.NameEn,b.TagId,b.ImgId,b.Status,pbg.ProductId,pbg.BrandId
				from ProductBrandGroup pbg left join Brand b
				ON pbg.BrandId = b.Id
				WHERE 1 and pbg.ProductId in ('.$str.')';

		$result = $this->query($sql,$productIds);
		if($result){
			while($result->fetch_assoc()){
				$resArr[$result->getData('ProductId')]['BrandId'] = $result->getData('BrandId');
				$resArr[$result->getData('ProductId')]['Status'] = $result->getData('Status');
				$resArr[$result->getData('ProductId')]['ImgId'] = $result->getData('ImgId');
				$resArr[$result->getData('ProductId')]['TagId'] = $result->getData('TagId');
				$resArr[$result->getData('ProductId')]['NameCn'] = $result->getData('NameCn');
				$resArr[$result->getData('ProductId')]['NameEn'] = $result->getData('NameEn');
				$resArr[$result->getData('ProductId')]['Name'] = $result->getData('NameCn') ? $result->getData('NameCn') : $result->getData('NameEn');
			}
		}
		return $resArr;
	}
	
}